﻿(function ($, dp) {
  var jobsAdmin = dp.JobsAdmin = dp.JobsAdmin || {};
  var jobsAdminUi = dp.JobsAdminUI = dp.JobsAdminUI || {};

  var newStock = dp.NewStock = dp.NewStock || {};
  var newStockUI = dp.NewStockUI = dp.NewStockUI || {};

  var utility = dp.Utility = dp.Utility || {};

  var environmentDropdown, manCoDropdown, documentTypeDropdown;

  var emptyMediaDefinitionsList, emptyStockAssignmentWindow, emptyMediaDefinitionAuditWindow, mailSortSettingSelector;

  (function initialisePage() {
    createJobsAdminFunctions();
    createNewStockFunctions();

    createJobsAdminUIReferences();
    createNewStockUIReferences();

    createJobsAdminUIFunctions();
    createNewStockUIFunctions();

    setJobsAdminUIEvents();
    setCreateStockUIEvents();

    pageLoad();
  })();

  function createJobsAdminFunctions() {

    jobsAdmin.getDocumentTypes = function (manCoCode) {

      var url = utility.getBaseUrl() + "/" + "DocTypes/Search";

      $.getJSON(url, { manCo: manCoCode }, function (data) {
        documentTypeDropdown.empty();

        documentTypeDropdown.append($('<option/>', {
          value: "",
          text: "Choose Document"
        }));

        $.each(data, function (index, code) {
          documentTypeDropdown.append($('<option/>', {
            value: code.Code,
            text: code.Description
          }));
        });
      });
    };

    jobsAdmin.getMediaDefinitions = function (page, environment, manCo, documentTypeCode, documentTypeName) {

      var url = utility.getBaseUrl() + "/" + "JobsAdmin/GetMediaDefinitionsAjax";
      url += '?page=' + page;
      url += '&environment=' + environment;
      url += '&manCoCode=' + manCo;
      url += '&documentTypeCode=' + documentTypeCode;
      url += '&documentTypeDescription=' + documentTypeName;

      $.ajax(url, {
        success: function (data) {
          var htmlTableResult = $(data).html();
          $('#JobList').html(htmlTableResult);
        },
        error: function (jqXHR) {
          alert('Error loading media definitions');
        }
      });
    }

    jobsAdmin.updatePrintFlagForMediaDefinition = function(mediaDefId, printValue, callback) {
      var url = utility.getBaseUrl() + "/" + "JobsAdmin/UpdatePrintFlag";
      url += '?mediaDefinitionId=' + mediaDefId;
      url += '&print=' + printValue;

      $.ajax(url, {
        type: "POST",
        success: function (jsonResult) {
          callback(jsonResult);
        },
        error: function (jqXHR) {
          alert('Error updating print flag');
        }
      });
    };

    jobsAdmin.updateMailSortSettingForMediaDefinition = function (mediaDefId, mailSortSettingId, callback) {
      var url = utility.getBaseUrl() + "/" + "JobsAdmin/UpdateMailSortSetting";
      url += '?mediaDefinitionId=' + mediaDefId;
      url += '&mailSortSettingId=' + mailSortSettingId;

      $.ajax(url, {
        type : "POST",
        success: function (jsonResult) {
          callback(jsonResult);
          },
          error: function (jqXHR) {
            alert('Error updating mail sort setting');
            }
          });
          };

    jobsAdmin.getManageStockWindow = function (mediaDefId, stockType, filter, callback) {
      var url = utility.getBaseUrl() + "/" + "JobsAdmin/AssignmentStockAjax";
      url += '?mediaDefinitionId=' + mediaDefId;
      url += '&stockType=' + stockType;
      url += '&filter=' + encodeURIComponent(filter);

      $.ajax(url, {
        success: function (htmlResult) {
          callback(htmlResult);
        },
        error: function (jqXHR) {
          alert('Error loading stock window');
        }
      });
    };

    jobsAdmin.removeMediaStock = function (mediaDefinitionId, stockType, mediaStockId, existingFilter, callback) {
      var url = utility.getBaseUrl() + "/" + "JobsAdmin/RemoveMediaStock";
      url += '?mediaDefinitionId=' + mediaDefinitionId;
      url += '&stockType=' + stockType;
      url += '&mediaStockId=' + mediaStockId;
      url += '&existingFilter=' + existingFilter;

      $.ajax(url, {
        type: "POST",
        success: function (htmlResult) {
          callback(htmlResult);
        },
        error: function (jqXHR) {
          alert('Error removing media stock item');
        }
      });
    }

    jobsAdmin.checkStationNumbersAreValid = function(mediaDefinitionId, stockType, stationNumberAssignments, callback) {
      var url = utility.getBaseUrl() + "/" + "JobsAdmin/UpdateStationNumbersValidityCheck";
      url += '?mediaDefinitionId=' + mediaDefinitionId;
      url += '&stockType=' + stockType;

      $.ajax(url, {
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "assignments": stationNumberAssignments }),
        success: function (jsonResult) {
          callback(jsonResult);
        },
        error: function (jqXHR) {
          alert('Error checking station numbers');
        }
      });
    };

    jobsAdmin.updateStationNumbers = function (mediaDefinitionId, stockType, stationNumberAssignments, callback) {
      var url = utility.getBaseUrl() + "/" + "JobsAdmin/UpdateStationNumbers";
      url += '?mediaDefinitionId=' + mediaDefinitionId;
      url += '&stockType=' + stockType;

      $.ajax(url, {
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "assignments" : stationNumberAssignments }),
        success: function (htmlResult) {
          callback(htmlResult);
        },
        error: function (jqXHR) {
          alert('Error updating station numbers');
        }
      });
    };

    jobsAdmin.checkCanAssignStockItems = function (mediaDefinitionId, stockType, stockItems, existingFilter, callback) {
      var url = utility.getBaseUrl() + "/" + "JobsAdmin/AddMediaStockIsAvailable";
      url += '?mediaDefinitionId=' + mediaDefinitionId;
      url += '&stockType=' + stockType;

      $.ajax(url, {
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "stockToAdd": stockItems }),
        success: function (jsonResult) {
          callback(jsonResult);
        },
        error: function (jqXHR) {
          alert('Error checking if stock items can be added');
        }
      });
    }

    jobsAdmin.getDefaultStationNumber = function(stockType, code) {
      switch (stockType) {
        case 'Outer':
          return '0';
        case 'LaserStock':
          switch(code) {
            case 'STATA':
              return '1';
            case 'STATB':
              return '2';
            case 'STATC':
              return '3';
            case 'STATD':
              return '4';
            case 'STATE':
              return '5';
            case 'STATF':
              return '6';
            default:
              return '';
          }
      default:
        return '';
      }
    };

    jobsAdmin.assignStockItems = function(mediaDefinitionId, stockType, stockItems, existingFilter, callback) {
      var url = utility.getBaseUrl() + "/" + "JobsAdmin/AddMediaStock";
      url += '?mediaDefinitionId=' + mediaDefinitionId;
      url += '&stockType=' + stockType;
      url += '&existingFilter=' + existingFilter;

      $.ajax(url, {
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "stockToAdd": stockItems }),
        success: function (htmlResult) {
          callback(htmlResult);
        },
        error: function (jqXHR) {
          alert('Error updating adding stock items');
        }
      });
    };

    jobsAdmin.getAuditWindow = function (mediaDefId, callback) {
      var url = utility.getBaseUrl() + "/" + "JobsAdmin/GetMediaDefinitionAuditsAjax";
      url += '?mediaDefinitionId=' + mediaDefId;

      $.ajax(url, {
        success: function (htmlResult) {
          callback(htmlResult);
        },
        error: function (jqXHR) {
          alert('Error loading audit window');
        }
      });
    };
  }

  function createNewStockFunctions() {

    newStock.getNewStockWindow = function (stockType, callback) {
      var url = utility.getBaseUrl() + "/" + "JobsAdmin/CreateStock";
      url += '?stockType=' + stockType;

      $.ajax(url, {
        success: function (htmlResult) {
          callback(htmlResult);
        },
        error: function (jqXHR) {
          alert('Error loading create stock window');
        }
      });
    };

    newStock.createStock = function (stockType, code, description, weight, sizeX, sizeY, facing, colour, callback) {

      var url = utility.getBaseUrl() + "/" + "JobsAdmin/CreateStock";

      var model = {
        stockType: stockType,
        code: code,
        description: description,
        weight: weight,
        sizeX: sizeX,
        sizeY: sizeY,
        facing: facing,
        colour: colour
      };

      $.ajax(url, {
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "model": model }),
        success: function (jsonResult) {
          callback(jsonResult);
        },
        error: function (jqXHR) {
          var errorMessage = 'Error creating new stock';
          alert(errorMessage);
        }
      });
    };
  }

  function createJobsAdminUIReferences() {
    environmentDropdown = $('#SelectedEnvironment');
    manCoDropdown = $('#SelectedManCo');
    documentTypeDropdown = $('#SelectedDocType');
  }

  function createNewStockUIReferences() {
    
  }

  function createJobsAdminUIFunctions() {

    jobsAdminUi.getDocumentTypes = function () {
      var manCoCode = manCoDropdown.val();
      jobsAdmin.getDocumentTypes(manCoCode);
    }

    jobsAdminUi.refreshMediaDefinitions = function() {
      var page = $('#mediaDefinitionsPagination span.current').text();
      jobsAdminUi.getMediaDefinitions(page);
    };

    jobsAdminUi.getMediaDefinitions = function (page) {
      var environment = environmentDropdown.val();
      var manCoCode = manCoDropdown.val();
      var docTypeCode = documentTypeDropdown.val();
      var docTypeName = documentTypeDropdown.find(':selected').text();
      jobsAdmin.getMediaDefinitions(page, environment, manCoCode, docTypeCode, docTypeName);
    }

    jobsAdminUi.clearMediaDefinitions = function () {
      $('#JobList').html(emptyMediaDefinitionsList);
    }

    jobsAdminUi.showStock = function (shownElement, toggleLink) {
      $(toggleLink).html('<span class="glyphicon glyphicon-minus-sign"></span>');
    };

    jobsAdminUi.hideStock = function (hiddenElement, toggleLink) {
      $(toggleLink).html('<span class="glyphicon glyphicon-plus-sign"></span>');
    };

    (function editMediaDefintionModule() {

      jobsAdminUi.editButtonClicked = function (triggerButton) {
        var mediaDef = triggerButton.closest('.media-definition-item');
        if (!mediaDef.hasClass('editmode')) {
          editMediaDefinition(mediaDef);
        } else {
          saveMediaDefinition(mediaDef);
        }
      };

      jobsAdminUi.cancelButtonClicked = function (triggerButton) {
        var mediaDefinitionItem = triggerButton.closest('.media-definition-item');
        var originalValue = mediaDefinitionItem.data('existing-printflag');
        var printCheckbox = mediaDefinitionItem.find('.print #print');
        printCheckbox.prop('checked', originalValue);

        leaveEditMode(mediaDefinitionItem);
      };

      function editMediaDefinition(mediaDefinitionItem) {
        enterEditMode(mediaDefinitionItem);
      };

      function enterEditMode(mediaDefinitionItem) {
        storeRollbackValues(mediaDefinitionItem);
        enterEditModeForItem(mediaDefinitionItem);
        enterEditModeForControls(mediaDefinitionItem);
      }

      function enterEditModeForItem(mediaDefinitionItem) {
        mediaDefinitionItem.addClass('editmode');

        var allMediaDefs = $('#mediaDefinitionsList .media-definition-item');
        var otherMediaDefs = allMediaDefs.not(mediaDefinitionItem);

        var otherActionButtons = otherMediaDefs.find('.btn-bbosaction');
        otherActionButtons.attr('disabled', 'disabled');

        var actionButtonGroup = mediaDefinitionItem.find('.btn-bbosaction').parent();
        var editButton = actionButtonGroup.find('.edit-button');
        editButton.text('Save');
        var otherButtons = actionButtonGroup.find('a').not(editButton);
        otherButtons.hide();

        actionButtonGroup.after('<button class="btn btn-bbosaction cancel-button" style="margin-left: 0.5em;"><span class="glyphicon glyphicon-remove coloured" /></button>');

        jobsAdminUi.collapseAllStockInfos();
        var allExpanderButtons = allMediaDefs.find('.togglecollapse');
        allExpanderButtons.on('click', null, disableExpanderEvent);
        allExpanderButtons.addClass("disabled");
      }

      function enterEditModeForControls(mediaDefinitionItem) {
        var printCheckbox = mediaDefinitionItem.find('.print #print');
        printCheckbox.removeAttr('disabled');

        var mailSortedItem = mediaDefinitionItem.find('.mailsorted');
        var mailSortId = mediaDefinitionItem.data('mailsortid');
        mailSortedItem.html(mailSortSettingSelector);
        mailSortedItem.find('select').val(mailSortId);
      }

      function storeRollbackValues(mediaDefinitionItem) {
        var printCheckbox = mediaDefinitionItem.find('.print #print');
        var isPrintChecked = printCheckbox.prop('checked');
        mediaDefinitionItem.data('existing-printflag', isPrintChecked);

        var mailSortCheckbox = mediaDefinitionItem.find('.mailsorted').html();
        mediaDefinitionItem.data('existing-mailsortcheckboxhtml', mailSortCheckbox);
      };

      function clearRollbackValues(mediaDefinitionItem) {
        mediaDefinitionItem.removeData('existing-printflag');
        mediaDefinitionItem.removeData('existing-mailsortcheckboxhtml');
      };

      function updateExistingValues(mediaDefinitionItem) {
        var mailSortedDropdown = mediaDefinitionItem.find('.mailsorted select');
        var mailSortSettingId = mailSortedDropdown.val();
        mediaDefinitionItem.data('mailsortid', mailSortSettingId);
      }

      function disableExpanderEvent() {
        return false;
      }

      function saveMediaDefinition(mediaDefinitionItem) {
        performSaveOfMediaDefinitionItem(mediaDefinitionItem);
        updateExistingValues(mediaDefinitionItem);
        leaveEditMode(mediaDefinitionItem);
      };

      function leaveEditMode(mediaDefinitionItem) {
        leaveEditModeForItem(mediaDefinitionItem);
        leaveEditModeForControls(mediaDefinitionItem);
        clearRollbackValues(mediaDefinitionItem);
      };

      function leaveEditModeForItem(mediaDefinitionItem) {
        var allActionButtons = $('#mediaDefinitionsList .media-definition-item .btn-bbosaction');
        allActionButtons.removeAttr('disabled');

        var actionButtonGroup = mediaDefinitionItem.find('.btn-bbosaction').parent();
        var editButton = actionButtonGroup.find('.edit-button');
        var otherButtons = actionButtonGroup.find('a').not(editButton);
        otherButtons.show();

        actionButtonGroup.siblings('.cancel-button').remove();
        editButton.text('Edit');

        var allMediaDefs = $('#mediaDefinitionsList .media-definition-item');
        var allExpanderButtons = allMediaDefs.find('.togglecollapse');
        allExpanderButtons.off('click', null, disableExpanderEvent);
        allExpanderButtons.removeClass("disabled");
      }

      function leaveEditModeForControls(mediaDefinitionItem) {
        var printCheckbox = mediaDefinitionItem.find('.print #print');
        printCheckbox.attr('disabled', 'disabled');

        var mailSortSettingElement = mediaDefinitionItem.find('.mailsorted');
        var mailSortSettingId = mediaDefinitionItem.data('mailsortid');
        var originalMailSortSettingHtml = mediaDefinitionItem.data('existing-mailsortcheckboxhtml');
        var isMailSorted = mailSortSettingId != 0;
        mailSortSettingElement.html(originalMailSortSettingHtml);
        var mailsortedCheckbox = mailSortSettingElement.find('#mailsorted');
        mailsortedCheckbox.prop('checked', isMailSorted);

        mediaDefinitionItem.removeClass('editmode');
      }

    function performSaveOfMediaDefinitionItem(mediaDefinitionItem) {

      var mediaDefId = mediaDefinitionItem.data('mediadefid');
      var printCheckbox = mediaDefinitionItem.find('.print #print');
        var isPrintChecked = printCheckbox.prop('checked');
        var existingPrintValue = mediaDefinitionItem.data('existing-printflag');
        if(isPrintChecked != existingPrintValue) {
          jobsAdmin.updatePrintFlagForMediaDefinition(mediaDefId, isPrintChecked, function () {
            // Do nothing
        });
        }

      var mailSortDropdown = mediaDefinitionItem.find('.mailsorted select');
      var mailSortSettingId = mailSortDropdown.val();
        var existingMailSortSettingId = mediaDefinitionItem.data('mailsortid');
        if (mailSortSettingId != existingMailSortSettingId) {
          jobsAdmin.updateMailSortSettingForMediaDefinition(mediaDefId, mailSortSettingId, function () {
            // Do nothing
          });
        }
        };

    })();

    jobsAdminUi.collapseAllStockInfos = function () {
      // Workaround for Bootstrap issue: https://github.com/twbs/bootstrap/issues/5859
      $('#mediaDefinitionsList .collapse').collapse({ 'toggle': false });

      $('#mediaDefinitionsList .collapse').collapse('hide');
    }

    jobsAdminUi.populateStockWindow = function (mediaDefId, stockType, title) {
      $('#stockAssignmentWindow .modal-title').text(title);

      var filter = $('#stockAssignmentWindow .filter input').val();

      jobsAdmin.getManageStockWindow(mediaDefId, stockType, filter, function (html) {
        $('#stockAssignmentWindow .modal-body').html(html);
      });
    };

    jobsAdminUi.refreshStockWindow = function () {
      var stockAssignmentWindow = $('#stockAssignmentWindow');
      var title = stockAssignmentWindow.find('.modal-title').text();
      var mediaDefinitionItem = stockAssignmentWindow.find('.mediadefinitionitem');
      var mediaDefId = mediaDefinitionItem.data('mediadefinitionid');
      var stockType = mediaDefinitionItem.data('stocktype');

      jobsAdminUi.populateStockWindow(mediaDefId, stockType, title);
    }

    jobsAdminUi.unassignMediaItem = function (triggerButton) {
      var mediaDefinitionItemElement = triggerButton.closest('.mediadefinitionitem');
      var mediaDefinitionId = mediaDefinitionItemElement.data('mediadefinitionid');
      var stockType = mediaDefinitionItemElement.data('stocktype');

      var mediaStockItem = triggerButton.closest('.mediastockitem');
      var mediaStockId = mediaStockItem.data('mediastockid');
      var code = mediaStockItem.find('.code').html();
      var filter = $('#stockAssignmentWindow .filter input').val();

      var confirmed = confirm('Are you sure you want to unassign stock item \'' + code + '\'?');

      if (confirmed) {
        jobsAdmin.removeMediaStock(mediaDefinitionId, stockType, mediaStockId, filter, function(htmlResult) {
          $('#stockAssignmentWindow div.modal-body').html(htmlResult);
        });
      }
    };

    function allowEditingStationNumbers() {
      var shouldAllowEditingStationNumbers = $('#stockAssignmentWindow .assignment-control').data('allow-editing-station-numbers');
      return Boolean(shouldAllowEditingStationNumbers) === true;
    };

    var editStationNumberExistingText = '';

    jobsAdminUi.editStationNumbers = function(triggerButton, availableItemsTable) {
      var stationNumberElements = availableItemsTable.find('td.stationNumber');

      stationNumberElements.each(function (index, item) {
        var existingContent = item.textContent;
        var newContent = '<input type="text" value="' + existingContent + '" />';
        $(item).html(newContent);
      });

      stationNumberElements.first().find('input').focus();

      editStationNumberExistingText = triggerButton.text();
      triggerButton.text('Save Changes');

      jobsAdminUi.checkSelectedItemsAreValid();
    };

    jobsAdminUi.checkStationNumberUpdatesAreValid = function () {
      var availableItemsTable = $('#assignedItems');
      var mediaDefinitionItemElement = availableItemsTable.closest('.mediadefinitionitem');

      var mediaDefinitionId = mediaDefinitionItemElement.data('mediadefinitionid');
      var stockType = mediaDefinitionItemElement.data('stocktype');

      var stationNumberElements = availableItemsTable.find('td.stationNumber');

      var newStationNumberAssignments = [];

      stationNumberElements.each(function (index, item) {
        var stationNumber = $(item).find('input').val();
        var mediaStockId = $(item).closest('.mediastockitem').data('mediastockid');

        newStationNumberAssignments.push({ mediaStockId: mediaStockId, stationNumber: stationNumber });
      });

      jobsAdmin.checkStationNumbersAreValid(mediaDefinitionId, stockType, newStationNumberAssignments, function (jsonResult) {
        var stationNumbersAreValid = jsonResult.Result;
        $('#btnEditStationNumbers').prop('disabled', !stationNumbersAreValid);
      });
    };

    jobsAdminUi.saveChangesToStationNumbers = function (triggerButton, availableItemsTable) {
      var mediaDefinitionItemElement = availableItemsTable.closest('.mediadefinitionitem');

      var mediaDefinitionId = mediaDefinitionItemElement.data('mediadefinitionid');
      var stockType = mediaDefinitionItemElement.data('stocktype');

      var stationNumberElements = availableItemsTable.find('td.stationNumber');

      var newStationNumberAssignments = [];

      stationNumberElements.each(function (index, item) {
        var stationNumber = $(item).find('input').val();
        var mediaStockId = $(item).closest('.mediastockitem').data('mediastockid');

        newStationNumberAssignments.push({ mediaStockId : mediaStockId, stationNumber : stationNumber });
      });

      jobsAdmin.updateStationNumbers(mediaDefinitionId, stockType, newStationNumberAssignments, function (result) {
        var resultInnerHtml = $(result).html();
        $('#assignedItems').html(resultInnerHtml);

        triggerButton.text(editStationNumberExistingText);

        jobsAdminUi.checkSelectedItemsAreValid();
      });
    };

    jobsAdminUi.selectAvailableItem = function (checkbox) {
      var availableItemRow = checkbox.closest('tr');
      var stationNumberElement = availableItemRow.find('.stationNumber');
      var code = availableItemRow.find('.code').html();
      var stockType = $('#stockAssignmentWindow .assignment-control').data('stocktype');

      var defaultStationNumber = jobsAdmin.getDefaultStationNumber(stockType, code);

      var allowEditingOfStationNumbers = allowEditingStationNumbers();

      if (allowEditingOfStationNumbers) {
        stationNumberElement.html('<input type="text" value="' + defaultStationNumber + '" />');
      } else {
        stationNumberElement.html(defaultStationNumber);
      }
      
    };

    jobsAdminUi.deselectAvailableItem = function(checkbox) {
      var stationNumberElement = checkbox.closest('tr').find('.stationNumber');
      stationNumberElement.html('');
    };

    jobsAdminUi.checkSelectedItemsAreValid = function () {
      var selectedStockItemRows = $('#availableItems input.includeitem:checked').closest('.stockitem');

      var mediaDefinitionId = $('#assignedItems').closest('.mediadefinitionitem').data('mediadefinitionid');
      var stockType = $('#assignedItems').closest('.mediadefinitionitem').data('stocktype');

      var filter = $('#stockAssignmentWindow .filter input').val();

      var allowEditingOfStationNumbers = allowEditingStationNumbers();

      var newStockItems = [];

      selectedStockItemRows.each(function (index, stockItemRow) {
        stockItemRow = $(stockItemRow);

        var stockId = stockItemRow.data('stockid');

        var stationNumber;
        if (allowEditingOfStationNumbers) {
          stationNumber = stockItemRow.find('.stationNumber input').val();
        } else {
          stationNumber = stockItemRow.find('.stationNumber').html();
        }

        newStockItems.push({ "stockId": stockId, "stationNumber": stationNumber });
      });

      if (newStockItems.length == 0) {
        $('#btnAssignSelectedItems').prop('disabled', true);
        return;
      }

      jobsAdmin.checkCanAssignStockItems(mediaDefinitionId, stockType, newStockItems, filter, function (jsonResult) {
        var assignmentsAreValid = jsonResult.Result;
        $('#btnAssignSelectedItems').prop('disabled', !assignmentsAreValid);
      });
    };

    jobsAdminUi.assignSelectedAvailableItems = function () {
      var selectedStockItemRows = $('#availableItems input.includeitem:checked').closest('.stockitem');

      var mediaDefinitionId = $('#assignedItems').closest('.mediadefinitionitem').data('mediadefinitionid');
      var stockType = $('#assignedItems').closest('.mediadefinitionitem').data('stocktype');

      var filter = $('#stockAssignmentWindow .filter input').val();

      var allowEditingOfStationNumbers = allowEditingStationNumbers();

      var newStockItems = [];

      selectedStockItemRows.each(function (index, stockItemRow) {
        stockItemRow = $(stockItemRow);

        var stockId = stockItemRow.data('stockid');

        var stationNumber;
        if (allowEditingOfStationNumbers) {
          stationNumber = stockItemRow.find('.stationNumber input').val();
        } else {
          stationNumber = stockItemRow.find('.stationNumber').html();
        }

        newStockItems.push({ "stockId": stockId, "stationNumber": stationNumber });
      });

      jobsAdmin.assignStockItems(mediaDefinitionId, stockType, newStockItems, filter, function (result) {
        $('#stockAssignmentWindow div.modal-body').html(result);
      });
    };

    jobsAdminUi.populateAuditWindow = function (mediaDefId, title) {
      $('#mediaDefinitionAuditWindow .modal-title').text(title);

      jobsAdmin.getAuditWindow(mediaDefId, function (html) {
        $('#mediaDefinitionAuditWindow .modal-body').html(html);
      });
    };

  }

  function createNewStockUIFunctions() {

    newStockUI.populateCreateStockWindow = function (triggerButton) {
      $('#stockCreationWindow .modal-title').text('');
      $('#stockCreationWindow .modal-body').html('');

      var mediaDefinitionItem = $(triggerButton).closest('.mediadefinitionitem');
      var stockType = mediaDefinitionItem.data('stocktype');
      var stockName = mediaDefinitionItem.data('displaystocktypesingular');

      newStock.getNewStockWindow(stockType, function (html) {
        $('#stockCreationWindow .modal-title').text('Create new ' + stockName + ' stock');
        $('#stockCreationWindow .modal-body').html(html);
      });
    };

    newStockUI.createStock = function () {

      var stockType = $('#StockType').val();
      var code = $('#Code').val();
      var description = $('#Description').val();
      var weight = $('#Weight').val();
      var sizeX = $('#SizeX').val();
      var sizeY = $('#SizeY').val();
      var facing = $('#Facing').val();
      var colour = $('#Colour').val();

      newStock.createStock(stockType, code, description, weight, sizeX, sizeY, facing, colour, function (jsonData) {
        if (jsonData.Success) {
          jobsAdminUi.refreshStockWindow();
          $('#stockCreationWindow').modal('hide');
        } else {
          var message = '';
          $.each(jsonData.Failures, function (index, value) {
            if (message !== '') {
              message += '<br />';
            }
            message += value;
          });
          displayErrors(message);
        }
      });
    };

    function displayErrors(message) {
      message = '<div class="alert alert-danger">' + message + '</div>';
      $('#message').html(message);
    }
  }

  function setJobsAdminUIEvents() {

    manCoDropdown.change(function () {
      jobsAdminUi.clearMediaDefinitions();
      jobsAdminUi.getDocumentTypes();
    });

    documentTypeDropdown.change(function () {

      if (documentTypeDropdown.val() == "") {
        jobsAdminUi.clearMediaDefinitions();
        return;
      }

      jobsAdminUi.getMediaDefinitions(1);
    });

    // Override pager default behaviour
    $('#JobList').on('click', '#mediaDefinitionsPagination a', function () {

      var page;

      if (isNaN(this.text)) {
        page = $('#mediaDefinitionsPagination span.current').text();
        if (this.text === '«') {
          page--;
        } else if (this.text === '»') {
          page++;
        }
      } else {
        page = this.text;
      }

      jobsAdminUi.getMediaDefinitions(page);
    });

    $('#JobList').on('show.bs.collapse', '.collapse', function (e) {
      var shownElement = e.target;
      var toggleLinkId = shownElement.attributes['data-target'].value;
      var toggleLink = document.getElementById(toggleLinkId);
      jobsAdminUi.showStock(shownElement, toggleLink);
    });

    $('#JobList').on('hide.bs.collapse', '.collapse', function (e) {
      var hiddenElement = e.target;
      var toggleLinkId = hiddenElement.attributes['data-target'].value;
      var toggleLink = document.getElementById(toggleLinkId);
      jobsAdminUi.hideStock(hiddenElement, toggleLink);
    });

    $('body').on('click', '#mediaDefinitionsList .edit-button', function (e) {
      e.preventDefault();
      var triggerButton = $(e.target);
      jobsAdminUi.editButtonClicked(triggerButton);
    });

    $('body').on('click', '#mediaDefinitionsList .cancel-button', function (e) {
      e.preventDefault();
      var triggerButton = $(e.target);
      jobsAdminUi.cancelButtonClicked(triggerButton);
    });

    (function multiLevelModalWorkaround() {
      // Workaround to make bootstrap support multi-level modal windows
      $('.modal').on('show.bs.modal', function () {
        var idx = $('.modal:visible').length;
        $(this).css('z-index', 1040 +(10 * idx));
        });
      $('.modal').on('shown.bs.modal', function() {
        var idx = ($('.modal:visible').length) - 1;
        $('.modal-backdrop').not('.stacked').css('z-index', 1039 +(10 * idx));
        $('.modal-backdrop').not('.stacked').addClass('stacked');
        });
    })();

    $('#stockAssignmentWindow').on('show.bs.modal', function (e) {

      $('#stockAssignmentWindow').html(emptyStockAssignmentWindow);

      var linkButton = $(e.relatedTarget);
      var title = linkButton.text();
      var stockType = linkButton.data('stocktype');
      var mediaDefId = linkButton.closest('tr').data('mediadefid');

      jobsAdminUi.collapseAllStockInfos();
      jobsAdminUi.populateStockWindow(mediaDefId, stockType, title);
    });

    $('#mediaDefinitionAuditWindow').on('show.bs.modal', function (e) {

      $('#mediaDefinitionAuditWindow').html(emptyStockAssignmentWindow);

      var linkButton = $(e.relatedTarget);
      var title = linkButton.data('windowtitle');
      var mediaDefId = linkButton.closest('tr').data('mediadefid');

      jobsAdminUi.populateAuditWindow(mediaDefId, title);
    });

    $('#stockAssignmentWindow').on('hide.bs.modal', function(e) {
      jobsAdminUi.refreshMediaDefinitions();
    });

    $('#stockAssignmentWindow').on('change', '.filter input', function (e) {
      jobsAdminUi.refreshStockWindow();
    });

    $('#stockAssignmentWindow').on('click', '.removeMediaItem', function (e) {
      var triggerButton = $(e.target);
      jobsAdminUi.unassignMediaItem(triggerButton);
    });

    $('#stockAssignmentWindow').on('click', '#btnEditStationNumbers', function (e) {
      var triggerButton = $(e.target);
      var targetTableId = triggerButton.data('target-table');
      var targetTable = $(targetTableId);

      if (triggerButton.text()!=='Save Changes') {
        jobsAdminUi.editStationNumbers(triggerButton, targetTable);
      } else {
        jobsAdminUi.saveChangesToStationNumbers(triggerButton, targetTable);
      }
    });

    $('#stockAssignmentWindow').on('change', '#assignedItems .stationNumber input', function () {
      jobsAdminUi.checkStationNumberUpdatesAreValid();
    });

    $('#stockAssignmentWindow').on('change', 'input.includeitem', function (e) {
      var isChecked = e.target.checked;
      var checkbox = $(e.target);

      if (isChecked) {
        jobsAdminUi.selectAvailableItem(checkbox);
      } else {
        jobsAdminUi.deselectAvailableItem(checkbox);
      }

      jobsAdminUi.checkSelectedItemsAreValid();
    });

    $('#stockAssignmentWindow').on('change', '#availableItems .stationNumber input', function () {
      jobsAdminUi.checkSelectedItemsAreValid();
    });

    $('#stockAssignmentWindow').on('click', '#btnAssignSelectedItems', function (e) {
      jobsAdminUi.assignSelectedAvailableItems();
    });
  }

  function setCreateStockUIEvents() {

    $('#stockCreationWindow').on('show.bs.modal', function (e) {
      var triggerButton = e.relatedTarget;
      newStockUI.populateCreateStockWindow(triggerButton);
    });

    $('#stockCreationWindow').on('click', '#createStock', function (e) {
      e.preventDefault();
      newStockUI.createStock();
    });
  }

  function pageLoad() {
    emptyMediaDefinitionsList = $('#JobList').html();
    emptyStockAssignmentWindow = $('#stockAssignmentWindow').html();
    emptyMediaDefinitionAuditWindow = $('#mediaDefinitionAuditWindow').html();

    $('#mailSortSettingSelector').removeClass('hide');
    mailSortSettingSelector = $('#mailSortSettingSelector')[0].outerHTML;
    $('#mailSortSettingSelector').remove();
  }

}(jQuery, DocProcessing));